<?php

/**
 * Created by PhpStorm.
 * User: Yieong
 * Date: 16/4/5
 * Time: 上午10:19
 */
class GlobalService extends Service{


    
    public static function indexHeader(){
    	return array(
    			'id'              => array('text' => 'ID', 'rule' => 'int'),
    			'server_id'       => array('text' => '服务器','width' => '350px'),
    			'send_type'       => array('text' => '发送类型'),
    			'title'           => array('text' => '邮件标题'),
    			'content'         => array('text' => '邮件内容','width' => '350px'),
    			'item'            => array('text' => '道具'),
    			'create_user'       => array('text' => '添加人'),
    			'create_time'       => array('text' => '创建时间'),
    			'status'            => array('text' => '状态'),
    			'action'            => array('text' => '操作')
    			//'synchro_time'       => array('text' => '同步时间'),
    	);
    }
    
    public static function indexData($params){
    	$user = AccAuth::me();
    	if($user['IsAdmin'] != 1 && $user['AddBy'] != 1){
    		$params['create_user'] = $user['UserID'];
    	}
    	
    	$modSendGlobal = new ModSendGlobal();
    	$result = $modSendGlobal->select($params);
    
    	$sendType = self::sendType();
    	$userList = self::userList();
    	$statusList = self::status();
    	$serverList = PubServer::getOptions($platform, $game, 'id');
    	foreach($result as &$v){
    		$v['content'] = '<div style="white-space:normal;">'.$v['content'].'</div>';
    		$item_array = json_decode($v['item'],true);
    		$item = '';
    		foreach ($item_array as $key=>$val){
    			if($val['is_bind'] == 1){
    				$bind = '绑定';
    			}
    			if($val['is_bind'] == 0){
    				$bind = '不绑定';
    			}
    			$item .= $val['item_name'].'-'.$val['item_id'].'-'.$val['item_number'].'-'.$bind;
    			$item .= '</br>';
    		}
    		$v['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
    		$v['item'] = $item;
    		$v['send_type'] = $sendType[$v['send_type']];
    		$v['create_user'] = $userList[$v['create_user']];
    		
    		$server_array = explode(',', $v['server_id']);
    		$server_name = '';
    		foreach ($server_array as $key=>$val){
    			$server_name .= ','.$serverList[$val];
    		}
    		$server_name = substr($server_name, 1);
    		$v['server_id'] = '<div style="white-space:normal;">'.$server_name.'</div>';
    		
    		$status = $v['status'];
    		if($status == 1){
    			$v['status'] = $statusList[$v['status']];
    		}
    		if($status == 2){
    			$v['status'] = '<font color="blue">'.$statusList[$v['status']].'</font>';
    			$v['action'] .= '<a href="javascript:;" name="xinfo" data-id="'.$v['id'].'"><font color="blue">审批信息</font></a>';
    		}
    		if($status == 3){
    			$v['status'] = '<font color="red">'.$statusList[$v['status']].'</font>';
    			$v['action'] .= '<a href="javascript:;" name="xinfo" data-id="'.$v['id'].'"><font color="blue">审批信息</font></a>';
    		}
    		
//    		$v['action']         = ' <a href="'.PubFunc::buildUrl('/oss/?r=global/delete').'&id='.$v['id'].'" confirm="是否要删除该条服信息?">删除</a>';
    		
    		$id = $v['id'];
//     		if($v['synchro_time'] == ''){
//     			$v['server_name'] = '<a href="JavaScript:void(0);" name="synchro_one" data-id="'.$v['id'].'" >同步</a>';
//     			$v['synchro_time'] = '未同步';
//     			$checkbox = '<input value="'.$v['id'].'" name="id" type="checkbox">&nbsp;&nbsp;';
    			 
//     		}else{
//     			$v['synchro_time'] = date('Y-m-d H:i:s', $v['synchro_time']);
//     			$checkbox = '<input value="'.$v['id'].'" name="id" disabled="disabled" type="checkbox">&nbsp;&nbsp;';
//     		}
//     		$v['id'] = $checkbox.$v['id'];
    	}
    	unset($v);
    
    	return $result;
    }
    
    public static function approveHeader(){
    	return array(
    			'id'                => array('text' => 'ID', 'rule' => 'int'),
    			'server_id'         => array('text' => '服务器'),
    			'send_type'         => array('text' => '发送类型'),
    			'title'             => array('text' => '邮件标题'),
    			'content'           => array('text' => '邮件内容','width' => '350px'),
    			'item'              => array('text' => '道具'),
    			'create_user'       => array('text' => '添加人'),
    			'create_time'       => array('text' => '创建时间'),
    			'status'            => array('text' => '状态'),
    			'action'            => array('text' => '操作')
    	);
    }
    
    public static function approveData($params){   	
    	$modSendGlobal = new ModSendGlobal();
    	$result = $modSendGlobal->page($params);
    
    	$sendType = self::sendType();
    	$userList = self::userList();
    	$statusList = self::status();
    	$serverList = PubServer::getOptions($platform, $game, 'id');
    	foreach($result['data'] as &$v){
    		$v['content'] = '<div style="white-space:normal;">'.$v['content'].'</div>';
    		$item_array = json_decode($v['item'],true);
    		$item = '';
    		foreach ($item_array as $key=>$val){
    			if($val['is_bind'] == 1){
    				$bind = '绑定';
    			}
    			if($val['is_bind'] == 0){
    				$bind = '不绑定';
    			}
    			$item .= $val['item_name'].'-'.$val['item_id'].'-'.$val['item_number'].'-'.$bind;
    			$item .= '</br>';
    		}
    		$v['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
    		$v['item'] = $item;
    		$v['send_type'] = $sendType[$v['send_type']];
    		$v['create_user'] = $userList[$v['create_user']];
    
    		$server_array = explode(',', $v['server_id']);
    		$server_name = '';
    		foreach ($server_array as $key=>$val){
    			$server_name .= ','.$serverList[$val];
    		}
    		$server_name = substr($server_name, 1);
    		$v['server_id'] = $server_name;
    
    	    $status = $v['status'];
			if($status == 1){
				$v['status'] = '<span class="xstatus">'.$statusList[$v['status']].'</span>';
				$v['action'] .= '<div class="xaction">';
				$v['action'] .= '<a href="javascript:;" name="approve" data-id="'.$v['id'].'"><font color="blue">批准</font></a>';
				$v['action'] .= '&nbsp;&nbsp;&nbsp;<a href="javascript:;" name="reject" data-id="'.$v['id'].'"><font color="red">驳回</font></a>';
				$v['action'] .= '</div>';
			}
			if($status == 2){
				$v['status'] = '<font color="blue">'.$statusList[$v['status']].'</font>';
				$v['action'] .= '<a href="javascript:;" name="xinfo" data-id="'.$v['id'].'"><font color="blue">审批信息</font></a>';
			}
			if($status == 3){
				$v['status'] = '<font color="red">'.$statusList[$v['status']].'</font>';
				$v['action'] .= '<a href="javascript:;" name="xinfo" data-id="'.$v['id'].'"><font color="blue">审批信息</font></a>';
			}
    		
			$id = $v['id'];
			$checkbox = '<input value="'.$v['id'].'" data-status="'.$v['show_status'].'" data-tmp="'.$v['open_time'].'" data-wlk="'.$v['is_wlk'].'" name="id" type="checkbox">&nbsp;&nbsp;';
			$v['id'] = $checkbox.$v['id'];

    	}
    	unset($v);
    
    	return $result;
    }
    
    public static function doAdd($params){
    	if(PubFunc::checkEmpty($params, array('send_type','title','content'))){
    		return array('state' => false, 'msg' => '缺少必要参数.');
    	}   
    	$serverList = PubServer::getOptions($platform, $game, 'id');
    	//请求接口，接口成功再入库
    	//$result = self::send($params);
    	$result['state'] = true;
    	if($result['state']){
    		$user = AccAuth::me();
    		$modSendGlobal = new ModSendGlobal();
    		
    		$item = '';
    		if($params['is_send_good'] == 2){ //不发送道具
    			$item = '';
    		}
    		if($params['is_send_good'] == 1){ //发送道具
    			$person_item = array();
    			foreach ($params['item_id'] as $key=>$val){
    				$data = array();
    				$data['item_name'] = $params['item_name'][$key];
    				$data['item_id'] = $params['item_id'][$key];
    				$data['item_number'] = $params['item_number'][$key];
    				$data['is_bind'] = $params['is_bind'][$key];
    				array_push($person_item, $data);
    			}
    			$item = json_encode($person_item);
    		}
    		
    		$server_array = array_unique($params['server_id']);
    		$server_id = implode(',', $server_array);
    		$server_name = '';
    		foreach ($server_array as $key=>$val){
    			$server_name .= ','.$serverList[$val];
    		}
    		$server_name = substr($server_name, 1);
    		
    		$modSendGlobal->platform      = 'test';
    		$modSendGlobal->game          = $params['g'];
    		$modSendGlobal->server_id  = $server_id;
    		$modSendGlobal->server_name   = $server_name;
    		$modSendGlobal->send_type    = $params['send_type'];
    		$modSendGlobal->title       = $params['title'];
    		$modSendGlobal->content       = $params['content'];
    		$modSendGlobal->item = $item;
    		$modSendGlobal->create_user   = $user['UserID'];
    		$modSendGlobal->create_time   = time();
    		$modSendGlobal->update_user   = $user['UserID'];
    		$modSendGlobal->update_time   = time();
    		$result = $modSendGlobal->save();
    		return array('state' => true, 'msg' =>'添加成功');
    	}else{
    		return array('state' => false, 'msg' => $result['msg']);
    	}
    		
    }
    
    public static function delete($id){
    	if(empty($id)) return false;
    
    	$modSendGlobal = new ModSendGlobal();
    	$modSendGlobal->deleteByPk($id);
    	return true;
    }



    public static function send($params){
        $accessory = array();
        foreach($params['item_id'] as $k=>$v){
            if(!empty($v) && !empty($params['item_number'][$k])){
                $accessory['item'][] = array(
                    'type'  => 1,
                    'id'    => $v,
                    'nums'  => intval($params['item_number'][$k]),
                	'name'  => $params['item_name'][$k],
                	'is_bind' => $params['is_bind'][$k],
                );
            }
        }


        $params['attached'] = $accessory;

        $api = new ApiService($params['server']);

        $args = array(
            'sendtype'      => $params['send_type'],
            'title'         => $params['title'],
            'content'       => $params['content'],
            'attached'      => $params['attached'],
        );
        $args['attached']   = json_encode($args['attached']);
        $result = $api->sendGlobalMail($args);
        return $result;
    }

    public static function  sendType(){
        return array(
            '1' => '全服发送',
            '2' => '在线玩家发送'
        );
    }
    
    public static function synchro($ids,$servers){
    	$modSendGlobal = new ModSendGlobal();
    	$serverList = PubServer::getOptions($platform, $game, 'id');
    	 
    	$ids_array = explode(',', $ids);
    	 
    	$server_array = explode(',', $servers);
    	$server_array = array_unique($server_array);
    	 
    	$info_res = '';
    	foreach ($ids_array as $key=>$val){
    		$obj = $modSendGlobal->findByPk($val);
    		$info = $obj->getAttributes();
    		$params = array();
    		$params['sendtype'] = $info['send_type'];
    		$params['title'] = $info['title'];
    		$params['content'] = $info['content'];
    		$info['item'] = json_decode($info['item'],true);
    		$item_array = array();
    		foreach($info['item'] as $k=>$v){
    			$item_array[$k]['type'] = 1;
    			$item_array[$k]['id'] = $v['item_id'];
    			$item_array[$k]['nums'] = $v['item_number'];
    			$item_array[$k]['name'] = $v['item_name'];
    			$item_array[$k]['is_bind'] = $v['is_bind'];
    		}
    		$accessory['item'] = $item_array;
    		$params['attached'] = json_encode($accessory);
    		$info_res .= '全服道具/货币发送ID为 <font color="red">'.$info['id'].'</font>';
    		$server_id = '';
    		$server_name = '';
    		foreach ($server_array as $key1=>$val1){
    			$params['server'] = $val1;
    			$api = new ApiService($params['server']);
    			unset($params['server']);
    			$result = $api->sendGlobalMail($params);
    			//$result['state'] = true;
    			if($result['state']){
    				$server_id .= ','.$val1;
    				$server_name .= ','.$serverList[$val1];
    				$info_res .= ' 发送服务器 <font color="red">'.$serverList[$val1].' </font>成功<br/>';
    			}else{
    				$info_res .= ' 发送服务器 <font color="red">'.$serverList[$val1].' </font>失败，失败原因'.$result['msg'].'<br/>';
    			}
    		}
    		
    		if($server_id != '' && $server_name != ''){
    			$server_id = substr($server_id, 1);
    			$server_name = substr($server_name, 1);
    			$update = array();
    			$update['server_id']     = $server_id;
    			$update['server_name']     = $server_name;
    			$update['synchro_time']  = time();
    			$modSendGlobal->updateByPk($info['id'], $update);
    		}
    		
    	}
    	return $info_res;
    	 
    }

    public static function status(){
    	return array(
    			'1' => '未批准',
    			'2' => '已批准',
    			'3' => '已驳回',
    	);
    }

    public static function get($id){
    	$modSendGlobal = new ModSendGlobal();
    	$obj = $modSendGlobal->findByPk($id);
    
    	if($obj){
    		$info = $obj->getAttributes();
    		return $info;
    	}else{
    		return false;
    	}
    }

    public static function getApproval($id){
    	$modSendGlobal = new ModSendGlobal();
    	$obj = $modSendGlobal->findByPk($id);
    
    	if($obj){
    		$result = array();
    		$info = $obj->getAttributes();
    		if($info['approval_info'] == ''){
    			return $result;
    		}    		
    		$approval_info_array = explode(';', $info['approval_info']);
    		$userList = self::userList();
    		foreach ($approval_info_array as $key=>$val){
    			$listOne = json_decode($val,true);
    			$listOne['user'] = $userList[$listOne['user']];
    			$result[] = $listOne;
    		}
    		return $result;
    	}else{
    		return false;
    	}
    }
    
    /**
     * 驳回
     * @param unknown $id
     * @param unknown $status
     * @return multitype:number string
     */
    public static function reject($id){
    	if(empty($id)){
    		$result = array('status'=>0,'msg'=>'参数不完整','data'=>'');
    		return $result;
    	}
    	 
    	$modSendGlobal = new ModSendGlobal();
    	$user = AccAuth::me();
    	$obj = $modSendGlobal->findByPk($id);
    	 
    	if(!$obj){
    		$result = array('status'=>0,'msg'=>'参数错误','data'=>'');
    		return $result;
    
    	}
    	$info = $obj->getAttributes();

    	$approval_info = '驳回';
    	$approval['time'] = date('Y-m-d H:i',time());
    	$approval['user'] = $user['UserID'];
    	$approval['info'] = $approval_info;
    	 
    	$update = array();
    	$update['status'] = 3;
    	$update['approval_user'] = trim($info['approval_user'].','.$user['UserID'],',');
    	$update['approval_info'] = trim($info['approval_info'].';'.json_encode($approval),';');  //审批信息
    	$mresult = $modSendGlobal->updateByPk($id, $update);
    	 
    	if($mresult){
    		$result = array('status'=>1,'msg'=>'操作成功','data'=>'');
    		return $result;
    	}else{
    		$result = array('status'=>1,'msg'=>'操作失败','data'=>'');
    		return $result;
    	}
    	 
    }
    
    /**
     * 批准
     */
    public static function approve($id){
    	if(empty($id)){
    		$result = array('status'=>0,'msg'=>'参数不完整','data'=>'');
    		return $result;
    	}
    	
    	$modSendGlobal = new ModSendGlobal();
    	$user = AccAuth::me();
    	$obj = $modSendGlobal->findByPk($id);
    	
    	if(!$obj){
    		$result = array('status'=>0,'msg'=>'参数错误','data'=>'');
    		return $result;
    	
    	}
    	$info = $obj->getAttributes();
    	if($info['server_id'] == ''){
    		$result = array('status'=>0,'msg'=>'参数错误','data'=>'');
    		return $result;
    	}
    	$result_info = self::sendVer2($info);
    	$status = 2;
    	if($result_info['is_all_success'] == 0){ //部分失败或者全部失败
    		$status = 3;
    	} 	
    	
    	$approval_info = $result_info['info_res'];
    	$approval['time'] = date('Y-m-d H:i',time());
    	$approval['user'] = $user['UserID'];
    	$approval['info'] = $approval_info;
    	
    	$update = array();
    	$update['status'] = $status;
    	$update['approval_user'] = trim($info['approval_user'].','.$user['UserID'],',');
    	$update['approval_info'] = trim($info['approval_info'].';'.json_encode($approval),';');  //审批信息
    	$update['synchro_time']  = time();
    	$mresult = $modSendGlobal->updateByPk($id, $update);
    	
    	if($mresult){
    		$result = array('status'=>1,'msg'=>'操作成功,'.$approval_info,'data'=>$status);
    		return $result;
    	}else{
    		$result = array('status'=>0,'msg'=>'操作失败','data'=>'');
    		return $result;
    	}
    }
    
    /**
     * 批量驳回
     * @param unknown $ids
     * @param unknown $status
     * @return multitype:number string
     */
    public static function batchReject($ids){
    	if(empty($ids)){
    		$result = array('status'=>0,'msg'=>'参数不完整','data'=>'');
    		return $result;
    	}
    
    	$modSendGlobal = new ModSendGlobal();
    	$user = AccAuth::me();
    	$game = PubBase::getCurrentGame();
    	$sendList = $modSendGlobal->getListForIds($game,$ids);
    	if(count($sendList) == 0){
    		$result = array('status'=>0,'msg'=>'数据不存在','data'=>'');
    		return $result;
    	}
    	
    	$fin_info = '';
    	$new_status_array = array();
    	foreach ($sendList as $key=>$val){
    		$info = $val;
    		$approval_info = '序号 <font color="red">'.$info['id'].'</font> 的申请驳回<br/>';
    		$fin_info .= $approval_info;
    		$approval['time'] = date('Y-m-d H:i',time());
    		$approval['user'] = $user['UserID'];
    		$approval['info'] = $approval_info;
    		$update = array();
    		$update['status'] = 3;
    		$update['approval_user'] = trim($info['approval_user'].','.$user['UserID'],',');
    		$update['approval_info'] = trim($info['approval_info'].';'.json_encode($approval),';');  //审批信息
    		$mresult = $modSendGlobal->updateByPk($info['id'], $update);
    		$new_status = 3;
    		$new_status_array[] = $new_status;
    	}
    	
    	$result = array('status'=>1,'msg'=>'操作成功，'.$fin_info,'data'=>$new_status_array);
    	return $result;
    
    }
    
    /**
     * 批量批准
     */
    public static function batchApprove($ids){
    	if(empty($ids)){
    		$result = array('status'=>0,'msg'=>'参数不完整','data'=>'');
    		return $result;
    	}

    	$modSendGlobal = new ModSendGlobal();
    	$user = AccAuth::me();
    	$game = PubBase::getCurrentGame();
    	$sendList = $modSendGlobal->getListForIds($game,$ids);
    	
    	if(count($sendList) == 0){
    		$result = array('status'=>0,'msg'=>'数据不存在','data'=>'');
    		return $result;
    	}
    	 
    	$fin_info = '';
    	$new_status_array = array();
    	foreach ($sendList as $key=>$val){
    		$info = $val;
    		if($info['server_id'] == ''){
    			$fin_info .= '序号 <font color="red">'.$info['id'].'</font> 的申请参数错误,原因服务器为空<br/>';
    			continue;
    		}
    		
    		$result_info = self::sendVer2($info);
    		$status = 2;
    		if($result_info['is_all_success'] == 0){ //部分失败或者全部失败
    			$status = 3;
    		}
    		
    		$approval_info = $result_info['info_res'];
    		$fin_info .= '序号 <font color="red">'.$info['id'].'</font> 的申请执行情况'.$approval_info;
    		$approval['time'] = date('Y-m-d H:i',time());
    		$approval['user'] = $user['UserID'];
    		$approval['info'] = $approval_info;
    		
    		$update = array();
    		$update['status'] = $status;
    		$update['approval_user'] = trim($info['approval_user'].','.$user['UserID'],',');
    		$update['approval_info'] = trim($info['approval_info'].';'.json_encode($approval),';');  //审批信息
    		$update['synchro_time']  = time();
    		$mresult = $modSendGlobal->updateByPk($info['id'], $update);
    		
    		$new_status_array[] = $status;
    	}
    	
    	$result = array('status'=>1,'msg'=>'操作成功，'.$fin_info,'data'=>$new_status_array);
    	return $result;
    }
    
    /**
     * 发送请求
     * @param unknown $info
     */
    public static function sendVer2($info){
    	$params = array();
    	$params['sendtype'] = $info['send_type'];
    	$params['title'] = $info['title'];
    	$params['content'] = $info['content'];
    	$info['item'] = json_decode($info['item'],true);
    	$item_array = array();
    	foreach($info['item'] as $k=>$v){
    		$item_array[$k]['type'] = 1;
    		$item_array[$k]['id'] = $v['item_id'];
    		$item_array[$k]['nums'] = $v['item_number'];
    		$item_array[$k]['name'] = $v['item_name'];
    		$item_array[$k]['is_bind'] = $v['is_bind'];
    	}
    	$accessory['item'] = $item_array;
    	$params['attached'] = json_encode($accessory);
    	//$info_res .= '全服道具/货币发送ID为 <font color="red">'.$info['id'].'</font>';
    	$info_res ='批准<br/>';
    	$server_id = '';
    	$server_array = explode(',', $info['server_id']);
    	$serverList = PubServer::getOptions($platform, $game, 'id');
    	$is_all_success = 1; //是否全部成功，1全部成功，0部分失败或者全部失败
    	foreach ($server_array as $key=>$val){
    		$params['server'] = $val;
    		$api = new ApiService($params['server']);
    		unset($params['server']);
    		$result = $api->sendGlobalMail($params);
    		//$result['state'] = true;
    		if($result['state']){
    			$server_name .= ','.$serverList[$val];
    			$info_res .= '发送服务器 <font color="red">'.$serverList[$val].' </font>成功<br/>';
    		}else{
    			$is_all_success = 0; //存在部分失败，则该申请为驳回
    			$info_res .= '发送服务器 <font color="red">'.$serverList[$val].' </font>失败，失败原因<font color="red">'.$result['msg'].'</font>,该申请自动驳回<br/>';
    		}
    	}
    	
    	$data = array('info_res'=>$info_res,'is_all_success'=>$is_all_success);
    	return $data;
    }

}